//////////////////////////////////////////////////////////////////////////////
//                                                                          //
//     Filename: KenoXMLTranslator.h                                         //
//  Create date: August 23, 2004                                            //
//                                                                          //
//////////////////////////////////////////////////////////////////////////////
//                                                                          //
//  Description: This file describes the KenoXMLTranslator class.  This class//
//                is a protocol translator that translates from the RTG     //
//                Tri-Card Poker protocol to XML and back.                  //
//                                                                          //
//////////////////////////////////////////////////////////////////////////////
//       Copyright (c) 2004 - Realtime Gaming.  All rights reserved.        //
//////////////////////////////////////////////////////////////////////////////

#include <windows.h>
#include <stdio.h>
#include "lib.h"
#include "KenoXMLTranslator.h"
#include "XMLDoc.h"
#include "endian.h"
#include "log.h"
#include "card.h"
#include "kenoproto.h"


//////////////////////////////////////////////////////////////////////////////
// Constructor
//////////////////////////////////////////////////////////////////////////////
KenoXMLTranslator::KenoXMLTranslator( Server* pServer, Connection* pParent ) : 
                                             XMLTranslator( pServer, pParent, 12, 1 )
{
}

//////////////////////////////////////////////////////////////////////////////
// Destructor
//////////////////////////////////////////////////////////////////////////////
KenoXMLTranslator::~KenoXMLTranslator()
{
}

/////////////////////////////////////////////////////////////////////////////
// TranslateIncomingMessage
//////////////////////////////////////////////////////////////////////////////
bool8 KenoXMLTranslator::TranslateIncomingMessage( uint8* pGameInBuff,  
												  uint32 nGameInBuffSize, 
												  uint8* pOutBuff, 
												  uint32 nOutBuffSize )
{
    bool8 bRetVal = false;

	// Handle the messages.  Note, I'm only going to look at the first character
	//  in a small attempt to optimize a bit
	switch( m_sMsgID[0] )
	{
		case 'L':
			bRetVal = TranslateInLogin( m_pDoc, pGameInBuff, nGameInBuffSize );
			break;

		case 'B':
        {
            if(m_sMsgID[1]=='a')
            {
                bRetVal = TranslateInBalance( m_pDoc, pGameInBuff, nGameInBuffSize, GetNumBytesMsgLen() );
            }
            else
            {
                bRetVal = TranslateInBet( m_pDoc, pGameInBuff, nGameInBuffSize );
            }

			break;
        }
		default:
			String sMsg = TEXT("Error, received unknown client message: ");
			sMsg += m_sMsgID;
			Log::msgError( sMsg );
			break;
	}

	// Report Error
	if( !bRetVal )
	{
		if ( m_sMsgID[0] == 'L' )
		{
			// Set an error into the out buffer
			ReturnLoginError( pOutBuff, nOutBuffSize );
		}
		else
		{
			// Set an error into the out buffer
			ReturnErrorMessage( TEXT("ServerError"), pOutBuff, nOutBuffSize );

			String sMsg = TEXT("Error translating incoming message: ");
			sMsg += m_sMsgID;
			Log::msgError( sMsg );
		}
	}

	return bRetVal;
}

//////////////////////////////////////////////////////////////////////////////
// TranslateOutgoingMessage
//////////////////////////////////////////////////////////////////////////////
uint32 KenoXMLTranslator::TranslateOutgoingMessage( uint8* pOutBuff, 
												   uint32 nOutBuffSize, 
												   uint8* pGameOutBuff, 
												   uint32 nGameOutBuffSize, 
												   uint32 nTotalGameBytes    )
{
	bool8 bResult = true;
	uint32 nGameBytesUsed = 0;
	uint32 nOutBytesUsed = 0;

	while ( bResult && (nGameBytesUsed < nTotalGameBytes) )
	{
		// Keep track of buffers as we might be processing more than one game
		//   message at a time.
		uint8* pCurGameBuf     = pGameOutBuff     + nGameBytesUsed;
		uint32 nCurGameBufSize = nGameOutBuffSize - nGameBytesUsed;
		uint8* pCurOutBuf      = pOutBuff         + nOutBytesUsed;
		uint32 nCurOutBufSize  = nOutBuffSize     - nOutBytesUsed;

		// Make sure buffer has not been overrun!
		if ( nOutBytesUsed > nOutBuffSize )
		{
			ASSERT(false);
			Log::msgError( "Error, out buffer overflow!" );
			return 0;
		}

		// Now the actual message handlers!
		switch( pCurGameBuf[1] )
		{

			case 'L':
				bResult = TranslateOutLogin( pCurOutBuf, nCurOutBufSize, pCurGameBuf, nCurGameBufSize );
				break;

			case 'B':
				bResult = TranslateOutBet( pCurOutBuf, nCurOutBufSize, pCurGameBuf, nCurGameBufSize );
				break;

			case 'm':
				bResult = TranslateOutBalance( pCurOutBuf, nCurOutBufSize, pCurGameBuf, nCurGameBufSize, 1 );
				break;

			case 'E':
				bResult = TranslateGenericOutError( pCurOutBuf, nCurOutBufSize, pCurGameBuf, nCurGameBufSize, 1 );
				break;

			case 'G':
			case 'N':
			case '$':
			case '!':
				bResult = TranslateOutError( pCurOutBuf, nCurOutBufSize, pCurGameBuf, nCurGameBufSize );
				break;

			default:
				bResult = ReturnErrorMessage( TEXT("UnknownMessage"), pCurOutBuf, nCurOutBufSize );
				Log::msgError( "Received unknown game message: %c", pCurGameBuf[1] );
				break;
		}

		// Check and see if any errors occurred
		if ( !bResult )
		{
			ReturnErrorMessage( TEXT("ParseError"), pCurOutBuf, nCurOutBufSize );
			Log::msgError( "Error translating outgoing message: %c", pCurGameBuf[1] );
		}

		// We know that the size of the message is always stored in the first
		//  byte of the client message.
		nGameBytesUsed += pCurGameBuf[0];

		// Out XML Messages are supposed to be NULL Terminated
		nOutBytesUsed += strlen( (char*) pCurOutBuf );
		nOutBytesUsed++;  // Add one for the NULL

		DEBUGMSG( ("\n***Outgoing: %s", pCurOutBuf) );
	}

	return nOutBytesUsed;
}

//****************************************************************************
// Incoming
//****************************************************************************

//////////////////////////////////////////////////////////////////////////////
// TranslateInLogin
//////////////////////////////////////////////////////////////////////////////
bool8 KenoXMLTranslator::TranslateInLogin( XMLDoc* pDoc, uint8* pGameInBuff, uint32 nGameInBuffSize )
{
    ////////////////////////////////////////////////////////////////
	// Login the user
	////////////////////////////////////////////////////////////////
    if ( !LoginUser( pDoc ) )
    {
        return false;
    }
    
    // Start by skipping the first byte of the message, that will be the
	//  length
	uint32 nOffset = 1;

	////////////////////////////////////////////////////////////////
	// Write Login for Keno
	////////////////////////////////////////////////////////////////
	pGameInBuff[nOffset++] = 'M';
	pGameInBuff[nOffset++] = 'L';
	pGameInBuff[nOffset++] = 'K';
	pGameInBuff[nOffset++] = 'N';

    String strGameType;
    if(!pDoc->GetSingleNodeText( TEXT("//game_id"), strGameType))
    {
        return false;
    }

    if(strGameType=="Keno")
    {
        m_nGameID = KENO_MACH_ID;
        pGameInBuff[nOffset++] = PROTO_VERSION1;
        pGameInBuff[nOffset++] = PROTO_VERSION2;
        pGameInBuff[nOffset++] = KENO_MACH_ID;
    }
	else
	{
		return false;
	}

	////////////////////////////////////////////////////////////////
	// Add ID
	////////////////////////////////////////////////////////////////
	if ( !AddLoginID( nOffset, pDoc, pGameInBuff ) )
	{
		return false;
	}
	
	////////////////////////////////////////////////////////////////
	// play for money/play for fun
	////////////////////////////////////////////////////////////////
	if ( !AddLoginMoneyType( nOffset, pDoc, pGameInBuff ) )
	{
		return false;
	}

	////////////////////////////////////////////////////////////////
	// Cient type: CSN-7534
	////////////////////////////////////////////////////////////////
	if ( !AddClientID( nOffset, pDoc, pGameInBuff ) )
	{
		return false;
	}

	////////////////////////////////////////////////////////////////
	// Authentication token. CSN-7075: New Authentication
	////////////////////////////////////////////////////////////////
	if ( !AddAuthenticationToken( nOffset, pDoc, pGameInBuff ) )
	{
		return false;
	}

	////////////////////////////////////////////////////////////////
	// Finally, add message size
	////////////////////////////////////////////////////////////////
	pGameInBuff[0] = (uint8) nOffset;

	return true;
}

//////////////////////////////////////////////////////////////////////////////
// TranslateInBet
//////////////////////////////////////////////////////////////////////////////
bool8 KenoXMLTranslator::TranslateInBet( XMLDoc* pDoc, uint8* pGameInBuff, uint32 nGameInBuffSize )
{
	// Message Size
	pGameInBuff[0] = 0;

	// Message ID
	pGameInBuff[1] = 'B';

    int32 nOffset=2;
	
	uint8 ucNumCards = 0;
	if ( !pDoc->GetSingleNodeByte( TEXT("//num_cards"), ucNumCards ) )
	{
		return false;
	}
	Endian::SendByte( ucNumCards, pGameInBuff + nOffset );

    nOffset += 1;

    uint8 ucGamesPerCard = 0;
	if ( !pDoc->GetSingleNodeByte( TEXT("//games_per_card"), ucGamesPerCard ) )
	{
		return false;
	}
	Endian::SendByte( ucGamesPerCard, pGameInBuff + nOffset );

    nOffset += 1;

    for(uint8 ucI = 0; ucI<ucNumCards; ++ucI)
    {
        String strCardCost;
        strCardCost.sprintf("//card_cost_%d",(int) ucI);

        uint16 usCardCost = 0;
        if ( !pDoc->GetSingleNodeShort( strCardCost, usCardCost ) )
	    {
		    return false;
	    }
        Endian::SendInt2( usCardCost, pGameInBuff + nOffset );

        nOffset += 2;

        String strNumPicks;
        strNumPicks.sprintf("//num_picks_card_%d",(int) ucI);

        uint8 ucNumPicks = 0;
	    if ( !pDoc->GetSingleNodeByte( strNumPicks, ucNumPicks ) )
	    {
		    return false;
	    }
	    Endian::SendByte( ucNumPicks, pGameInBuff + nOffset );

        nOffset += 1;

        for(uint8 ucJ=0;ucJ<ucNumPicks;++ucJ)
        {
            String strPick;
            strPick.sprintf("//pick_%d_%d",(int) ucI, (int) ucJ);

            uint8 ucPick = 0;
	        if ( !pDoc->GetSingleNodeByte( strPick, ucPick ) )
	        {
		        return false;
	        }
	        Endian::SendByte( ucPick, pGameInBuff + nOffset );

            nOffset += 1;
        }
    }

    pGameInBuff[0] = nOffset;

	return true;
}


//****************************************************************************
// Outgoing
//****************************************************************************

//////////////////////////////////////////////////////////////////////////////
// TranslateOutLogin
//////////////////////////////////////////////////////////////////////////////
bool8 KenoXMLTranslator::TranslateOutLogin( uint8* pOutBuff, 
										   uint32 nOutBuffSize, 
										   uint8* pGameOutBuff, 
										   uint32 nGameOutBuffSize )
{
	XMLDoc doc;

	if ( !doc.StartNew() )
	{
		return false;
	}

	if ( !doc.CreateRootNode( TEXT("game_msg") ) )
	{
		return false;
	}

	if ( !doc.AddRootChildNode( TEXT("msg_id"), TEXT("Login") ) )
	{
		return false;
	}

	// Keep track of offset in buffer
	uint32 nOffset = 2;

	// Balance 
	int32 nValue;
	Endian::ReceiveInt4( &nValue, pGameOutBuff + nOffset );
	if ( !doc.AddRootChildNode( TEXT("balance"), (uint32) nValue ) )
	{
		return false;
	}
	nOffset += 4;

	// Minimum Bet
	Endian::ReceiveInt4( &nValue, pGameOutBuff + nOffset );
	if ( !doc.AddRootChildNode( TEXT("min_bet"), (uint32) nValue ) )
	{
		return false;
	}
	nOffset += 4;

	// Maximum Bet
	Endian::ReceiveInt4( &nValue, pGameOutBuff + nOffset );
	if ( !doc.AddRootChildNode( TEXT("max_bet"), (uint32) nValue ) )
	{
		return false;
	}
	nOffset += 4;

	// max games per card
	uint8 nVal = pGameOutBuff[nOffset++];
	if ( !doc.AddRootChildNode( TEXT("max_games_per_card"), (uint32) nVal ) )
	{
		return false;
	}

	// paytable
	nVal = pGameOutBuff[nOffset++];
	if ( !doc.AddRootChildNode( TEXT("pay_table"), (uint32) nVal ) )
	{
		return false;
	}

    // denominations
    for(int32 nI=0;nI<5;++nI)
    {
	    String strTagName;
        strTagName.sprintf("denom_value_%d",nI);
	    Endian::ReceiveInt4( &nValue, pGameOutBuff + nOffset );
	    if ( !doc.AddRootChildNode( strTagName, (uint32) nValue ) )
	    {
		    return false;
	    }
	    nOffset += 4;
    }

	if ( !AddCurrencyOutput(&doc) )	// CSN-11204: return currency
	{
		return false;
	}

	// Done - send the actual XML
	if ( !doc.SendXML( pOutBuff, nOutBuffSize ) )
	{
		return false;
	}

	return true;
}

//////////////////////////////////////////////////////////////////////////////
// TranslateOutDeal
//////////////////////////////////////////////////////////////////////////////
bool8 KenoXMLTranslator::TranslateOutBet( uint8* pOutBuff, 
									      uint32 nOutBuffSize, 
										  uint8* pGameOutBuff, 
										  uint32 nGameOutBuffSize )
{
	XMLDoc doc;

	if ( !doc.StartNew() )
	{
		return false;
	}

	if ( !doc.CreateRootNode( TEXT("game_msg") ) )
	{
		return false;
	}

	if ( !doc.AddRootChildNode( TEXT("msg_id"), TEXT("Bet") ) )
	{
		return false;
	}

	// Keep track of offset in buffer
	uint32 nOffset = 2;

    int32 nNumGames = (((int32) pGameOutBuff[0]) - 6)/24;

    for(int32 nI=0;nI<nNumGames;++nI)
    {
        for(int32 nJ=0;nJ<20;++nJ)
        {
            String strPick;
            strPick.sprintf("pick_%d_%d", nI, nJ);
	        
	        uint8 nPick = pGameOutBuff[nOffset++];
	        if ( !doc.AddRootChildNode( strPick, (uint32) nPick ) )
	        {
		        return false;
	        }
        }

        String strPayout;
        strPayout.sprintf("payout_%d",nI);

        int32 nPayout;
        Endian::ReceiveInt4( &nPayout, pGameOutBuff + nOffset );
        nOffset += 4;

        if ( !doc.AddRootChildNode( strPayout, (uint32) nPayout ) )
        {
	        return false;
        }
    }

	// Balance 
	int32 nValue;
	Endian::ReceiveInt4( &nValue, pGameOutBuff + nOffset );
	if ( !doc.AddRootChildNode( TEXT("balance"), (uint32) nValue ) )
	{
		return false;
	}
	nOffset += 4;

	// Done - send the actual XML
	if ( !doc.SendXML( pOutBuff, nOutBuffSize ) )
	{
		return false;
	}

	return true;
}


//////////////////////////////////////////////////////////////////////////////
// TranslateOutError
//////////////////////////////////////////////////////////////////////////////
bool8 KenoXMLTranslator::TranslateOutError( uint8* pOutBuff, 
										   uint32 nOutBuffSize, 
										   uint8* pGameOutBuff, 
										   uint32 nGameOutBuffSize )
{
	bool8 bRetVal = false;

	if ( pGameOutBuff[1] == '$' )
	{
		bRetVal = ReturnErrorMessage( TEXT("InsufficientFunds"), pOutBuff, nOutBuffSize );
	}
	else if ( pGameOutBuff[1] == '!' )
	{
		bRetVal = ReturnErrorMessage( TEXT("Shutdown"), pOutBuff, nOutBuffSize );
	}
	else if ( pGameOutBuff[1] == 'B' )
	{
		bRetVal = ReturnErrorMessage( TEXT("InvalidBet"), pOutBuff, nOutBuffSize );
	}
	else if ( pGameOutBuff[1] == 'N' )
	{
        // kharmon.  02-21-07.  MCA #29819.  Need to send back different messages for auto and admin logoffs.
        String strErrorName = "InvalidAction";

        if(pGameOutBuff[0]==6)  // The extra 4 bytes have the error code.
        {
            int32 nErrorCode=0;
            Endian::ReceiveInt4( &nErrorCode, &pGameOutBuff[2] );

            switch(nErrorCode)
            {
                case TrackSQL::AdminLogout:
                {
                    strErrorName = "AdminLogout";
                    break;
                }
                case TrackSQL::AutoLogout:
                {
                    strErrorName = "TimedOut";
                    break;
                }
            }            
        }

        bRetVal = ReturnErrorMessage( strErrorName, pOutBuff, nOutBuffSize );
	}
	else if ( pGameOutBuff[1] == 'G' )
	{
		bRetVal = ReturnErrorMessage( TEXT("InProgress"), pOutBuff, nOutBuffSize );
	}

	return bRetVal;
}